#include "Mutex.h"

Mutex::Mutex()
{
#ifdef WIN32
	Handle = CreateMutex(NULL, FALSE, NULL);
	if (!Handle)
	{
		fprintf(stderr, "Mutex: Error creating mutex: %d.\n", GetLastError());
	}
#else
	pthread_mutex_init(&Handle, NULL);
#endif
}

Mutex::~Mutex()
{
#ifdef WIN32
	CloseHandle(Handle);
#else
	pthread_mutex_destroy(&Handle);
#endif
}

void Mutex::Lock()
{
#ifdef WIN32
	DWORD res;
	SetLastError(0);
	res = WaitForSingleObject(Handle, INFINITE);
	if (res != WAIT_OBJECT_0) // if false, mutex is locked
	{
		fprintf(stderr, "Mutex.Lock: Could not lock the mutex. %d, %d\n", res, GetLastError());
	}
#else
	pthread_mutex_lock(&Handle);
#endif
}

void Mutex::Unlock()
{
#ifdef WIN32
	ReleaseMutex(Handle);
#else
	pthread_mutex_unlock(&Handle);
#endif
}

AutoLock::AutoLock(Mutex& mut) : (Handle = mut)
{
	mut.Lock();
}

AutoLock::~AutoLock()
{
	mut.Unlock();
}
